<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.bookmanager.model.Category" %>
<%@ page import="java.util.List" %>
<%@ page import="com.bookmanager.model.User" %>
<%
    // 检查管理员权限
    User user = (User) session.getAttribute("user");
    if (user == null || !"admin".equals(user.getRole())) {
        response.sendRedirect("../login.jsp");
        return;
    }

    List<Category> categories = (List<Category>) request.getAttribute("categories");
%>
<html>
<head>
    <title>分类管理 - 图书管理系统</title>
    <style>
        /* 使用与 book-management.jsp 相同的样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f7fa;
            color: #333;
        }

        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 0 20px;
        }

        .nav-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            height: 70px;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }

        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .admin-badge {
            background: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .logout-btn {
            padding: 8px 16px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 0.9rem;
        }

        .container {
            max-width: 1000px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .page-title {
            font-size: 1.8rem;
            color: #333;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .category-table {
            width: 100%;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .category-table th,
        .category-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .category-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #555;
            border-bottom: 2px solid #e9ecef;
        }

        .category-table tr:hover {
            background: #f8f9fa;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .empty-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            font-size: 14px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.2);
        }

        .close {
            float: right;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            color: #666;
        }

        .close:hover {
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }

        .form-control:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="nav-bar">
        <div class="logo">📚 图书管理系统</div>
        <div class="admin-info">
            <span>欢迎，<strong><%= user.getUsername() %></strong></span>
            <span class="admin-badge">管理员</span>
            <a href="<%= request.getContextPath() %>/logout" class="logout-btn">退出登录</a>
        </div>
    </div>
</div>

<div class="container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">🏷️ 分类管理</h1>
        <div>
            <a href="../admin/dashboard.jsp" class="btn btn-primary">返回控制台</a>
            <button class="btn btn-success" onclick="showAddCategoryModal()">
                <span>➕</span> 添加分类
            </button>
        </div>
    </div>

    <!-- 消息提示 -->
    <%
        String message = request.getParameter("message");
        if (message != null) {
            String alertClass = "";
            String alertText = "";

            if ("add_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "分类添加成功！";
            } else if ("add_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "分类添加失败！";
            } else if ("update_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "分类更新成功！";
            } else if ("update_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "分类更新失败！";
            } else if ("delete_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "分类删除成功！";
            } else if ("delete_failed".equals(message)) {
                alertClass = "alert-danger";
                String error = request.getParameter("error");
                if ("has_books".equals(error)) {
                    alertText = "分类删除失败！该分类下还有图书，请先移除相关图书。";
                } else {
                    alertText = "分类删除失败！";
                }
            }

            if (!alertText.isEmpty()) {
    %>
    <div class="alert <%= alertClass %>">
        <%= alertText %>
    </div>
    <%      }
    }
    %>

    <!-- 分类表格 -->
    <% if (categories != null && !categories.isEmpty()) { %>
    <table class="category-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>分类名称</th>
            <th>描述</th>
            <th>图书数量</th>
            <th>创建时间</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <% for (Category category : categories) { %>
        <tr>
            <td><%= category.getCategoryId() %></td>
            <td><strong><%= category.getCategoryName() %></strong></td>
            <td><%= category.getDescription() != null ? category.getDescription() : "暂无描述" %></td>
            <td><%= category.getBookCount() != null ? category.getBookCount() : 0 %></td>
            <td><%= category.getCreateTime() != null ? category.getCreateTime().toLocalDate().toString() : "未知" %></td>
            <td>
                <div class="action-buttons">
                    <button class="btn btn-warning btn-sm" onclick="editCategory(<%= category.getCategoryId() %>)">编辑</button>
                    <button class="btn btn-danger btn-sm" onclick="deleteCategory(<%= category.getCategoryId() %>, '<%= category.getCategoryName() %>')">删除</button>
                </div>
            </td>
        </tr>
        <% } %>
        </tbody>
    </table>
    <% } else { %>
    <div class="empty-state">
        <div class="empty-icon">🏷️</div>
        <h3>暂无分类数据</h3>
        <p>请添加图书分类以更好地组织您的图书</p>
        <button class="btn btn-success" onclick="showAddCategoryModal()" style="margin-top: 15px;">
            <span>➕</span> 添加第一个分类
        </button>
    </div>
    <% } %>
</div>

<!-- 添加分类模态框 -->
<div id="addCategoryModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeAddCategoryModal()">&times;</span>
        <h2 style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">添加新分类</h2>

        <form id="addCategoryForm" action="book-categories" method="post">
            <input type="hidden" name="action" value="add">

            <div class="form-group">
                <label class="form-label">分类名称 *</label>
                <input type="text" name="categoryName" class="form-control" required
                       placeholder="请输入分类名称">
            </div>

            <div class="form-group">
                <label class="form-label">分类描述</label>
                <textarea name="description" class="form-control" rows="3"
                          placeholder="请输入分类描述"></textarea>
            </div>

            <div style="display: flex; gap: 10px; margin-top: 25px; padding-top: 15px; border-top: 1px solid #eee;">
                <button type="submit" class="btn btn-success" style="flex: 1;">添加分类</button>
                <button type="button" class="btn btn-primary" onclick="closeAddCategoryModal()">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
    function showAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'block';
    }

    function closeAddCategoryModal() {
        document.getElementById('addCategoryModal').style.display = 'none';
        document.getElementById('addCategoryForm').reset();
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('addCategoryModal');
        if (event.target === modal) {
            closeAddCategoryModal();
        }
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeAddCategoryModal();
        }
    });

    // 表单提交验证
    document.getElementById('addCategoryForm').addEventListener('submit', function(e) {
        const categoryName = this.querySelector('input[name="categoryName"]').value;

        if (!categoryName.trim()) {
            e.preventDefault();
            alert('请填写分类名称！');
            return;
        }
    });

    // 操作函数
    function editCategory(categoryId) {
        window.location.href = 'book-categories?action=edit&categoryId=' + categoryId;
    }

    function deleteCategory(categoryId, categoryName) {
        if (confirm('确定要删除分类 "' + categoryName + '" 吗？\n\n注意：如果该分类下还有图书，将无法删除。')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = 'book-categories';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'delete';
            form.appendChild(actionInput);

            const categoryIdInput = document.createElement('input');
            categoryIdInput.type = 'hidden';
            categoryIdInput.name = 'categoryId';
            categoryIdInput.value = categoryId;
            form.appendChild(categoryIdInput);

            document.body.appendChild(form);
            form.submit();
        }
    }
</script>
</body>
</html>
